// components/resources/resources.js
import {
    $wuxToast,
    $wuxDialog
} from '../../es/index'
Component({
    /**
     * 组件的属性列表
     */
    properties: {

    },

    /**
     * 组件的初始数据
     */
    data: {
        sort_up: "按时间升序",
        sort_down: "按时间降序",
        sort_type: 0, //0表示按时间升序，1表示按时间降序
        currentPage: 1,
        hasMorePages: true,
        fileList: [],
        downloadingTasks:[],
        value: '', //搜索内容
        isSearching: false,//判断是否在搜索中
        foundFiles: [],

    },

    /**
     * 组件的方法列表
     */
    methods: {
        //滑动到底部加载更多内容
        getMoreItems: function (e) {
            if (this.data.hasMorePages == false)
                return;
            wx.showLoading({
                title: '加载中',
            })
            var that = this
            var currentPage = that.data.currentPage + 1
            wx.request({
                url: 'https://szsyph.cn/file/getFileList',
                data: {
                    page: currentPage,
                },
                method: "GET",
                header: {
                    'content-type': 'application/json' // 默认值
                },
                success(res) {
                    wx.hideLoading();
                    var responseData = res.data;
                    var fileList = that.data.fileList;
                    //如果返回码为200说明获取成功
                    if (responseData.code == 200) {
                        var fileListNew = responseData.data.files;
                        if (fileListNew.length == 0) {
                            that.setData({
                                hasMorePages: false
                            })
                            that.showToast("forbidden", "没有更多内容啦", 500);
                        } else {
                            for (var i = 0; i < fileListNew.length; i++) {
                                fileList.push(fileListNew[i]);
                            }
                            that.setData({
                                currentPage: currentPage,
                                fileList: fileList
                            });
                        }
                    } else {
                        that.showToast("cancle", "出现了内部错误，请稍后再试")
                    }
                },
                fail: function (res) {
                    this.showToast("cancle", "网络问题,请稍后再试")
                },
            })
        },

        //搜索相关方法
        onChange(e) {
            this.setData({
                value: e.detail.value,
            })
        },
        onClear(e) {
            this.setData({
                value: '',
                isSearching: false,
                foundFile: []
            })
        },
        onCancel(e) {
            var keyword = this.data.value;
            var pattern = new RegExp(".*" + keyword + ".*");
            var foundFiles = [];
            //重置
            if (keyword == "") {
                this.setData({
                    isSearching: false
                })
            }
            //搜索
            else {
                var fileList = this.data.fileList
                for (var i = 0; i < fileList.length; i++) {
                    if (fileList[i].fileName.search(pattern) != -1) {
                        foundFiles.push(fileList[i]);
                    }
                }
                this.setData({
                    isSearching: true,
                    foundFiles: foundFiles
                })
            }
        },

        //弹出提示框
        //type可选为success、cancel、forbidden
        //分别代表成功、错误操作、警告操作
        showToast(type, text, time) {
            $wuxToast().show({
                type: type,
                duration: time,
                color: '#fff',
                text: text
            })
        },
        //下载文件
        downloadFile: function (e) {
            var that = this;
            var token = this.getToken();
            if (token) {
                var fid = e.currentTarget.dataset.fid;
                var index = e.currentTarget.dataset.index;
                var filename= e.currentTarget.dataset.filename;
                var downloadingTasks = this.data.downloadingTasks;
                downloadingTasks[index]=true;
                this.setData({
                    downloadingTasks:downloadingTasks
                })
                const downloadTask = wx.downloadFile({
                    url: 'https://szsyph.cn/file/download?fid=' + fid,
                    header: {
                        'cookie': "token=" + token
                    },
                    filePath:wx.env.USER_DATA_PATH+"/"+filename,
                    success: function (res) {
                        that.showToast("success", "下载成功", 1000);
                        wx.openDocument({
                            filePath: res.filePath,
                            fileType: "pdf",
                        });
                    },
                    complete:function(){
                        downloadingTasks[index] = false;
                        that.setData({
                            downloadingTasks:downloadingTasks
                        })
                    }
                });
                this.setData({
                    downloadTask: downloadTask
                })
            } else {
                wx.switchTab({
                    url: '/pages/profile/profile',
                })
            }
        },
        cancel: function () {
            this.data.downloadTask.abort();
        },
        //获取token
        getToken: function () {
            var deadtime = parseInt(wx.getStorageSync("tokenTime"));
            if (deadtime) {
                if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {

                    return null;
                }
            }
            //如果没有时间限制 或者 有时间限制但是没有过期
            var res = wx.getStorageSync("token");
            if (res) {
                return res
            } else {
                return null
            }
        },
        //和本地存储进行匹配，判断本地是否已经下载
        // RefineFileList: function (fileList) {
        //     var downloadedFiles = wx.getStorageSync('downloadedFiles');
        //     if (downloadedFiles == null)
        //         return fileList;
        //     else {
        //         for (var i = 0; i < fileList.length; i++) {
        //             for (var j = 0; j < downloadedFiles.length; j++) {
        //                 if (fileList[i].fid == downloadedFiles[j].fid) {
        //                     fileList[i].isDownloaded = true;
        //                     fileList[i].savedFilePath = downloadedFiles[j].savedFilePath;
        //                 }
        //             }
        //         }
        //     }
        //     return fileList;
        // }
    },

    lifetimes: {
        attached: function () {
            wx.showLoading({
                title: '加载中',
            })
            var that = this
            wx.request({
                url: 'https://szsyph.cn/file/getFileList',
                data: {
                    page: that.data.currentPage,
                },
                method: "GET",
                header: {
                    'content-type': 'application/json' // 默认值
                },
                success(res) {
                    wx.hideLoading();
                    var responseData = res.data;
                    if (res.data.code == 200) {
                        var fileList = responseData.data.files;
                        that.setData({
                            fileList: fileList
                        })
                    } else {
                        that.showToast("cancle", "出现了内部错误，请稍后再试", 800)
                    }
                },
                fail(res) {
                    wx.hideLoading();
                    that.showToast("cancle", "网络问题，请稍后再试", 800);
                }
            });
        },
    }
})